import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'

Vue.use(VueRouter)


const router = new VueRouter({
  routes: [
    { path: '/', redirect: 'login' },
    { path: '/login', component: Login },
    { path: '/home', component: Home }
  ]
})

// 为路由对象，添加beforeEach 导航守卫

router.beforeEach((to, from, next) => {
  // to表示要去哪个地址
  //from表示从哪个地址来，next表示放行
  //如果用户要访问登录页面，那直接放行
  if (to.path === '/login') next()

  const tokenStr = window.sessionStorage.getItem('token')

  //如果没有token，强制跳转login页面
  if (!tokenStr) return next('/login')
  next()

})



export default router
